﻿using System;
using System.Net;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;

namespace BallMadness
{
    public class ScoreManager
    {
        int playerScore = 0;
        List<Worm> worms;

        TimeSpan wormDelay = new TimeSpan(0, 0, 7);
        TimeSpan nextWorm;

        public static Texture2D worm;
        SpriteFont uifont;

        public static bool gameOver;
        

        public ScoreManager()
        {
            worms = new List<Worm>();
        }


        public void setScore(int score)
        {
            playerScore += score;
        }

        public int getScore()
        {
            return playerScore;
        }

        public void Reset()
        {
            gameOver = false;
            playerScore = 0;
            worms.Clear();
        }

        public void OnNavigateTo(ContentManager manager)
        {
            worm = manager.Load<Texture2D>("worm");
            uifont = manager.Load<SpriteFont>("ui");
        }

        public void OnUpdate(GameTimerEventArgs e)
        {
            nextWorm -= e.ElapsedTime;
            if (nextWorm <= TimeSpan.Zero && !ScoreManager.gameOver)
            {
                nextWorm = wormDelay;
                worms.Add(new Worm());
            }

            for (int c = worms.Count - 1; c >= 0; c--)
            {
                worms[c].OnUpdate(e);
                if (worms[c].isOffScreen())
                {
                    worms.RemoveAt(c);
                }
            }
        }

        

        public void OnDraw(SpriteBatch spriteBatch)
        {
            foreach (Worm w in worms)
                w.OnDraw(spriteBatch);

            spriteBatch.DrawString(
                uifont,
                "Score: " + playerScore,
                new Vector2(10, 10),
                Color.White);

            if (gameOver)
            {
                spriteBatch.DrawString(
                    uifont,
                    "GAME OVER",
                    new Vector2(30, SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height / 2),
                    Color.White);
            }
        }

        public void CheckCollision(int radius, Vector2 position)
        {
            for (int c = worms.Count - 1; c >= 0; c--)
            {
                if (worm.Height / 2 + radius > Vector2.Distance(position, worms[c].position))
                {
                    playerScore += Worm.POINTS;
                    worms.RemoveAt(c);
                }
            }
        }
    }
}
